<template>
  <el-dialog v-model="dialog.visible" :title="title" width="30%" @close="handleCloseDialog">
    <div class="form-container">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="130"
        class="form mb-0"
      >
        <el-form-item label="父级品类" prop="parentCode" v-if="isTop">
          <el-tree-select
            v-model="formData.parentCode"
            :data="treeData"
            node-key="code"
            check-strictly
            placeholder="请选择父级品类"
            :props="{ label: 'name' }"
            :render-after-expand="false"
            @current-change="handleCurrentChange"
          ></el-tree-select>
        </el-form-item>
        <el-form-item label="品类名称" prop="name">
          <el-input v-model.trim="formData.name" placeholder="请输入品类名称" />
        </el-form-item>
        <el-form-item label="品类代码" prop="code">
          <el-input :disabled="isEdit" v-model.trim="formData.code" placeholder="请输入品类代码" />
        </el-form-item>
        <el-form-item label="品类预算比例" prop="budgetRatio">
          <el-input-number
            v-model.trim="formData.budgetRatio"
            placeholder="请输入品类预算比例"
            :step="0.1"
            :min="0"
            :max="1"
            class="!w-[180px]"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleCloseDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ElMessage } from "element-plus";
import categoryApi, { SysMaterialCategoryForm } from "@/api/category/category-api";
import CommonAPI from "@/api/system/common";
import { arrayToTree } from "@/utils/common";
// 定义 emit，用于通知外部关闭事件
const emit = defineEmits(["update:modelValue", "loadData"]);
const dialog = reactive({
  title: "",
  visible: false,
});
/*基础信息*/
const formRef = ref();
const loading = ref(false);
const treeData = ref([]);
const title = computed(() => (formData.value.id ? "编辑" : "新增"));
const isEdit = computed(() => !!formData.value.id);
const iszxjc = computed(() => formData.value.parentCode === "zhuangXiuJianCai");
const isTop = computed(() => formData.value.level !== 1);
const defaultFormData: SysMaterialCategoryForm = {
  budgetRatio: undefined,
  code: "",
  id: undefined,
  name: "",
  parentCode: "",
};
const formData = ref({
  ...defaultFormData,
});
const formRules = reactive({
  parentCode: [{ required: true, message: "请选择父级品类", trigger: "change" }],
  name: [{ required: true, message: "请输入品类名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入品类代码", trigger: "blur" }],
  budgetRatio: [
    {
      type: "number",
      validator: (rule, value) => {
        return String(value).match(/^(0(\.\d+)?|1(\.0+)?)$/)
          ? Promise.resolve()
          : Promise.reject("值必须在 0 到 1 之间");
      },
    },
    { required: true, message: "请输入品类预算比例", trigger: "blur" },
  ],
});

async function handleSubmit() {
  const validate = await formRef.value.validate();
  if (!validate) return;
  try {
    if (formData.value.id) {
      await categoryApi.update(formData.value);
    } else {
      await categoryApi.add(formData.value);
    }
    ElMessage.success("成功");
    emit("loadData");
    handleCloseDialog();
  } catch (error) {
    console.log("error", error);
  }
}

// 关闭弹窗
function handleCloseDialog() {
  formData.value = {};
  Object.assign(formData.value, defaultFormData);
  dialog.visible = false;
  emit("update:modelValue", false); // 关闭弹窗
}

function showModal(val) {
  dialog.visible = true;
  Object.assign(formData.value, defaultFormData);
  getAllCategory();
  if (!val) return;
  getCategory(val.id);
}

async function getCategory(id) {
  try {
    const data = await categoryApi.getById(id);
    formData.value = { ...formData.value, ...data };
  } catch (e) {
    console.log(e);
  }
}

function handleCurrentChange(data, node) {
  formRef.value.budgetRatio = undefined;
}
function getAllCategory() {
  loading.value = true;
  CommonAPI.getAllMaterialCategory({
    isLeaf: false,
  })
    .then((data) => {
      treeData.value = arrayToTree(data || []);
    })
    .finally(() => {
      loading.value = false;
    });
}

defineExpose({
  showModal,
});
</script>
<style style="scss" scoped>
.form-container {
  height: 500px;
  overflow: auto;
}
.form {
  ::v-deep(.el-form-item) {
    margin-bottom: 0;
  }
}
</style>
